<?php

namespace App\Http\Controllers\Basic;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Mews\Captcha\Facades\Captcha;

class MiscController extends Controller
{
    public  function  city(Request $request)
    {
        $parentId = intval($request->input('parent_id', 0));

        $list = DB::table('area')->where('parent_id', $parentId)->orderby('id')->get()->toArray();

        $this->setData(["list"=>$list]);

        return $this->response();
    }

    public function cityByName(Request $request, $type)
    {
        $rules = ['name'=>'required', ];

        $validator = Validator::make(Input::all(), $rules);
        if($validator->fails())
        {
            $errors = $validator->errors();
            $this->setStatus(10001);
            $this->setMsg(implode(' ', $errors->all()));

            return $this->response();
        }

        switch($type)
        {
            case 'province':
                $level = 1;
                break;

            case 'city':
                $level = 2;
                break;

            case 'county':
                $level = 3;
                break;
        }

        $parent = DB::table('area')->where('level', $level)->where(function ($query){
            $query->where('name', request()->get('name'))->orwhere('short_name', request()->get('name'));
        })->orderby('sort')->first();

        $list = DB::table('area')->where('parent_id', $parent->id)->orderby('id')->get()->toArray();

        $this->setData(["list"=>$list]);

        return $this->response();
    }

    public function downloadUserData(Request $request, $date)
    {
        $file = storage_path('sync/'.$date.'.json');

        if(is_file($file))
        {
            return response()->download($file, $date.'.json');
        }

        return response('', 404);
    }
}
